from django.shortcuts import render
from django.views import View
import logging, json, re
from django import http
from apps.users.models import User
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.users.models import User
from apps.users.utils import check_email_verify_url, generate_email_verify_url
from celery_tasks.email.tasks import send_email_verify_url
from apps.users.models import Address

# Create your views here.

logger = logging.getLogger('django')


class RegisterView(View):
    def post(self, request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # json_dict = json.loads(request.body.decode())
        # json_dict = json.loads(request.body)

        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return http.JsonResponse({"code": 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({"code": 400, 'errmsg': 'username参数有误'})
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return http.JsonResponse({"code": 400, 'errmsg': '参数password有误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({"code": 400, 'errmsg': 'mobile参数有误'})
        if password != password2:
            return http.JsonResponse({"code": 400, 'errmsg': '两次密码输入不一致'})
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})
        if allow != True:
            return http.JsonResponse({"code": 400, 'errmsg': '未勾选协议'})

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        login(request, user)

        # 写入cookie，展示至页面
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # return http.JsonResponse({"code": 0, 'errmsg': '注册成功'})
        return response


class MobileCountView(View):
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({"code": 400, 'errmsg': '手机号错误'})

        return http.JsonResponse({"code": 0, 'errmsg': 'OK', 'count': count})


class UsernameCountView(View):
    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({"code": 400, 'errmsg': '用户名错误'})

        return http.JsonResponse({"code": 0, 'errmsg': 'ok', "count": count})


class LoginView(View):
    """用户登录"""

    def post(self, request):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        # username = json_dict.get('username')
        account = json_dict.get('username')
        password = json_dict.get('password')
        # 记住状态标志：True：已登录；False：未登录。可传可不传
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     return http.JsonResponse({"code": 400, 'errmsg': 'username参数有误'})
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return http.JsonResponse({"code": 400, 'errmsg': '参数password有误'})

        # 多账号登录
        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 认证用户
        # user = authenticate(request=request, username=username, password=password)
        user = authenticate(request=request, username=account, password=password)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或者密码错误'})

        # 实现状态保持
        login(request, user)
        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        # 写入cookie，展示至页面
        response = http.JsonResponse({'code': 0, 'errmsg': '登录成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 响应结果
        # return http.JsonResponse({'code': 0, 'errmsg': '登录成功'})
        return response


class LogoutView(View):
    """用户登录"""

    def delete(self, request):
        logout(request)
        response = http.JsonResponse({'code': 0, 'errmsg': '退出登录成功'})
        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心"""

    def get(self, request):
        data_dict = {
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active,
            },
        }
        return http.JsonResponse(data_dict)


# class UserInfoView(View):
#     """用户中心"""
#
#     def get(self, request):
#         """实现用户中心数据展示"""
#         if not request.user.is_authenticated:
#             return http.JsonResponse({'code': 400, 'errmsg': '用户未登录'})
#
#         data_dict = {
#             'code': 0,
#             'errmsg': 'OK',
#             'info_data': {
#                 'username': '',
#                 'mobile': '',
#                 'email': '',
#                 'email_active': '',
#             },
#         }
#
#         return http.JsonResponse(data_dict)


class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 赋值email字段
        try:
            request.user.email = email
            request.user.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱添加失败'})

        # 发送激活邮件
        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 400, "errmsg": 'OK'})


class EmailActiveView(View):
    """验证激活邮箱"""

    # 接受参数
    def put(self, request):
        # 接受参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})

        # 通过token提取要验证邮箱的用户对象
        user = check_email_verify_url(token=token)
        # 将要验证邮箱的用户email_active字段设置为True
        try:
            user.email_active = True
            user.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '邮箱验证成功'})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        # 获取地址的个数
        try:
            count = Address.objects.filter(user=request.user, is_deleted=False).count()
        except BaseException as e:
            return http.JsonResponse({'code': 400, 'errmsg': '获取地址数据出错'})

        # 判断是否超过地址上限
        if count > 20:
            return http.JsonResponse({'code': 400, 'errmsg': '地址数量超过上限'})

        # 接受参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        place = json_dict.get('place')
        district_id = json_dict.get('district_id')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "mobile": address.mobile,
            "place": address.place,
            "email": address.email,
            "tel": address.tel
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})


class AddressView(LoginRequiredJSONMixin, View):
    """用户收货地址展示"""

    def get(self, request):
        # 获取所有的地址
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return http.JsonResponse({'code': 0,
                                  'addresses': address_dict_list,
                                  'errmsg': 'OK',
                                  'default_address_id': default_id,
                                  'limit': 20})


class UpdateDestroyAddressView(View):
    """修改和删除地址"""
    def put(self, request, address_id):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 判断地址是否存在，并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                # title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id= city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            # "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除结果
        return http.JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(View):
    """设置默认地址"""
    def put(self, request, address_id):
        try:
            # 接收参数
            address = Address.objects.get(id=address_id)
            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址的结果
        return http.JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(View):
    """设置地址的标题"""
    def put(self, request, address_id):
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '设置标题地址成功'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    """实现密码修改逻辑"""
    def put(self, request):
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400, 'errmsg': '新密码格式错误'})
        if new_password != new_password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入新密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except BaseException as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.delete_cookie('username')

        # 响应结果
        return response
